from locust import HttpUser, task, constant
import hashlib
import threading
import time

class MyUser(HttpUser):
    wait_time = constant(0)  # 尽量快速发送请求
    login_successful = False  # 用于标记用户是否登录成功
    Supda_Auth = None
    host = "https://uat-api.child-healthy.com"
    completed_request = False
    lock = threading.Lock()  # 使用锁来同步用户登录和请求

    def on_start(self):
        # 在每个用户开始时执行登录操作
        self.login()

    def login(self):
        # 登录并获取token
        url = r'https://uat-api.child-healthy.com/supda-auth/oauth/token'
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
            'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
            'Origin': 'https://uat-admin.child-healthy.com',
        }
        # 将密码转换未MD532位编码
        password = "yzp123456"
        md = hashlib.md5()
        md.update(password.encode(encoding='UTF-8'))
        body = {"tenantId": "", "username": "yzp3", "password": md.hexdigest(),
                "grant_type": "password", "scope": "all", "type": "account"}
        response = self.client.post(url, data=body, headers=header)
        if response.status_code == 200:
            result = response.json()
            with self.lock:
                self.Supda_Auth = result.get('access_token')
                self.login_successful = True
        else:
            print("Login failed!")
            self.environment.runner.quit()

    @task
    def perform_action(self):
        # 等待所有用户完成登录
        while not self.login_successful:
            self.wait()

        # 所有用户都成功登录后，等待10秒，然后并发请求目标接口
        if self.login_successful and not self.completed_request:
            time.sleep(10)  # 等待3秒
            header = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
                'Supda-Auth': self.Supda_Auth,
                'Origin': 'https://uat-admin.child-healthy.com',
            }
            aiurl = r'https://uat-api.child-healthy.com/supda-nonpub/cloudCase/aiAnalysis'
            json_data = {"id": "1752528737269125121", "fileUrl": "https://supda-uat-1317091130.cos.ap-guangzhou.myqcloud.com/upload/20240131/fada67645d1f8062733458fbbd63e9cd.jpg"}
            self.client.post(aiurl, json=json_data, headers=header)
            self.completed_request = True


            '''
            设置x个用户，每秒新增y个
            当所有的用户全部登陆成功后，集体等待5s
            然后统一请求目标压测接口，所有用户仅请求一次，然后终止任务
            '''



# locust -f 压测骨龄AI解析.py --web-host=127.0.0.1 --host=https://uat-api.child-healthy.com -r 1 --users 10